﻿#include "KHIOModuleDevice.h"

#include <QJsonArray>
#include <QDebug>
#include <QtAlgorithms>

KHIOModuleDevice::KHIOModuleDevice(QObject *parent):BaseIOModule(parent)
{
}

bool KHIOModuleDevice::ReadStatus(QString ioName, bool &status)
{
    IOItem *item=GetIOItem(ioName);
    status=item->GetStatus();
    return true;
}

bool KHIOModuleDevice::WriteStatus(QString ioName, bool status)
{
    IOItem *item=GetIOItem(ioName);
    if(item->DeviceType()==IODeviceType::Output)
    {
        _modbus->WriteBits(item->Addr(),1,QList<bool>()<<status);
    }
    return true;
}

void KHIOModuleDevice::SetCommunication(QList<BaseCommunication *> communication)
{
    BaseIOModule::SetCommunication(communication);
    if(communication.empty())
    {
       throw QString("KHIOModuleDevice 未配置通讯实体!");
    }
    _modbus=dynamic_cast<BaseModbus*>(communication.first());
}

void KHIOModuleDevice::GetConnectStateCore(DeviceStateItems &items)
{
    if(_inReading)
    {
        return;
    }

    _inReading=true;
    QList<bool> ret;
    _modbus->ReadInBits(64,8,ret);
    QList<bool> allIo;
    _modbus->ReadOutBits(32,8,allIo);
    allIo.append(ret);

    for(int i=0;i<_allIOItems.count();i++)
    {
        _allIOItems.at(i)->SetStatus(allIo.at(i));
    }


    for(int i=0;i<items.count();i++)
    {
        bool status;
        if(FindStatus(items[i].DataType,status))
        {
            items[i].Data=QString::number(status);
        }
    }
    _inReading=false;
}

bool KHIOModuleDevice::FindStatus(QString dataType,bool &status)
{
    for(int i=0;i<_allIOItems.count();i++)
    {
        if(dataType==_allIOItems[i]->GetName())
        {
            status=_allIOItems.at(i)->GetStatus();
            return true;
        }
    }
    return false;
}



